import { COURSELIST } from '../../../configs/api';
import store from '../../../utils/file'
import { request } from '../../../utils/request';
import userApi from '../userApi/index';

const getCourses = async (_uid: string, _d: string, vc3: string): Promise<CourseType[] | string> => {
  let formdata = `courseType=1&courseFolderId=0&courseFolderSize=0`
  let res = await request({
    url: COURSELIST.URL,
    method: COURSELIST.METHOD as any,
    header: {
      'Accept': 'text/html, */*; q=0.01',
      'Accept-Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;',
      'Cookie': `_uid=${_uid}; _d=${_d}; vc3=${vc3}`
    },
    data: formdata,
  })
  if (res.statusCode == 302) return "AuthFailed";
  // 解析出所有 courseId 和 classId，填充到数组返回
  const data = res.data as string;
  let arr: CourseType[] = []
  for (let i = 1; ; i++) {
    i = data.indexOf('course_', i)
    if (i == -1) break
    const end_of_courseid = data.indexOf('_', i + 7)
    const end_of_course_name = data.indexOf('"', data.indexOf('title="', i) + 7);
    const start_of_teacher_name = data.indexOf('title="', data.indexOf('title="', end_of_course_name) + 7) + 7
    const end_of_teacher_name = data.indexOf('"', start_of_teacher_name)
    arr.push({
      courseId: data.slice(i + 7, end_of_courseid),
      classId: data.slice(end_of_courseid + 1, data.indexOf('"', i + 1)),
      imgSrc: data.slice(data.indexOf('img src="', i) + 9, data.indexOf('"', data.indexOf('img src="', i) + 9)),
      title: data.slice(data.indexOf('title="', i) + 7, end_of_course_name).replace('&nbsp;', ' '),
      teacher: data.slice(start_of_teacher_name, end_of_teacher_name).replace('&nbsp;', ' ').replace('&nbsp;', ' '),
    })
  }
  return arr;
}


function storeCourses(cources: CourseType[]) {
  return store.set('cources', cources);
}


async function getCoursesLocal(latest = false):Promise<CourseType[] | string> {
  if (latest) {
    const params = userApi.getUser(userApi.getCurUser())
    const courses = await getCourses(params._uid!, params._d!, params.vc3!)
    if (typeof courses != 'string') {
      storeCourses(courses);
    }
    return courses;
  }
  let courses: string | CourseType[] = store.get('cources');
  if (!courses) {
    const params = userApi.getUser(userApi.getCurUser())
    courses = await getCourses(params._uid!, params._d!, params.vc3!)
    if (typeof courses != 'string') {
      storeCourses(courses);
    }
  }
  return courses;
}

export default {
  storeCourses,
  getCourses,
  getCoursesLocal
}